﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace ECCIT.Diagnostics
{
    public class Logger
    {
        #region private variables

        private string _logFilePath;
        private bool _writeToConsole;
        private static Mutex mutex = new Mutex ();

        #endregion

        public static Logger Empty
        {
            get { return new Logger (string.Empty, true); }
        }

        public string LogFilePath
        {
            get { return _logFilePath; }
            set { _logFilePath = value; }
        }

        public Logger (string logFilePath, bool writeToConsole)
        {
            _logFilePath = logFilePath;
            _writeToConsole = writeToConsole;
        }

        public void WriteLog (string text)
        {
            if (text != null)
            {
                if (_writeToConsole)
                {
                    Console.WriteLine (text);
                }

                if (_logFilePath != string.Empty)
                {
                    mutex.WaitOne ();
                    File.AppendAllText (_logFilePath, "[" + DateTime.Now.ToLongTimeString () + "]");
                    File.AppendAllText (_logFilePath, text + Environment.NewLine);
                    mutex.ReleaseMutex ();
                }
            }
        }

        public void WriteException (Exception e, string text)
        {
            WriteLog ("\n*** " + text + " ***");
            WriteLog ("Error Message: " + e.Message);
            WriteLog ("Error Source: " + e.Source);
            WriteLog ("Error StackTrace: " + e.StackTrace);
        }
    }
}
